package cn.com.cfae.iras.doc.analyze.components.integrity;

import cn.com.cfae.iras.doc.analyze.beans.web.ContentAndPosition;
import cn.com.cfae.iras.doc.analyze.beans.web.Detail;
import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by 佟媛媛 on 18/10/23.
 */

@Component("I1004")
@Scope("prototype")
public class I1004 extends BaseComponent {

    private static Logger log = LoggerFactory.getLogger(I1004.class);

    @Autowired
    private I1001 i1001;

    /**
     * @auth 佟媛媛
     * @date 18/10/29 下午7:13
     * @desc
     * fxap.ms
     * 分销安排：提示位置，人工核对
     * 该表述为一般表述，非固定模式。若不一致，提示核对分销安排信息。
     * 1、检查分销安排文字描述≥3行，不满足提示人工核对；
     */
    @Override
    public List<ComponentResult> handlerM() {
       return common("M-3");
    }

    private List<ComponentResult> common(String catalogId){
        List<ComponentResult> list = new ArrayList<>();
        setCatalogId(catalogId);
        int pageNum = getChapterModel(getCatalogId()).getStartPage();
        try{
            i1001.setExtractData(getExtractData());
            i1001.setKeyword("分销安排");
            Map map = i1001.ifKeywordExist2(getCatalogId());
            boolean exist = (boolean)map.get("exist");
            if(exist){
                List<ContentAndPosition> contentAndPositionList = (List<ContentAndPosition>)map.get("contentAndPositionList");
                List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                if(!CollectionUtils.isEmpty(contentAndPositionList)){
                    for(ContentAndPosition contentAndPosition : contentAndPositionList){
                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                        textPosition.setX(contentAndPosition.getX());
                        textPosition.setY(contentAndPosition.getY());
                        textPosition.setContent(contentAndPosition.getContent());
                        textPositionList.add(textPosition);
                    }
                    pageNum = contentAndPositionList.get(0).getPageNum();
                }
                int currentPageNum  = pageNum;
                int nextPageNum = pageNum+1;
                int start = -1;
                int end = -1;
                int lines = 0;
                //匹配 （一）分销安排；(一)分销安排；一、分销安排；1、分销安排
                String title = "(((\\(|（)(一|二|三|四|五|六|七|八|九|十)(\\)|）))|(\\d{1,2}、)|((一|二|三|四|五|六|七|八|九|十)、))分销安排[\\S\\s]*";
                String nextTitle = "(((\\(|（)(一|二|三|四|五|六|七|八|九|十)(\\)|）))|((一|二|三|四|五|六|七|八|九|十)、))[\\S\\s]*";
                PageModel pageModel = getPageModel(getCatalogId(),currentPageNum);
                PageModel nextPageModel = getPageModel(getCatalogId(),nextPageNum);
                JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                if(jsonTextDataArray!=null){
                    boolean boo = false;
                    for(JsonElement element : jsonTextDataArray){
                        if(boo) break;
                        JsonArray data = element.getAsJsonObject()!=null?element.getAsJsonObject().getAsJsonArray("data"):null;
                        if(data!=null){
                            lines = data.size();
                            for(int i=0;i<data.size();i++){
                                JsonObject current = returnOne(data.get(i).getAsJsonArray());
                                if(Pattern.matches(title,current.get("text").getAsString())){
                                    start = i;
                                    break;
                                }
                            }
                            if(start!=-1){
                                for(int i=start+1;i<data.size();i++){
                                    if(boo) break;
                                    JsonObject current = returnOne(data.get(i).getAsJsonArray());
                                    if(Pattern.matches(nextTitle,current.get("text").getAsString())){
                                        end = i;
                                        boo = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if(end-start>=3 || (start!=-1 && end==-1 && lines-start>=3)){
                    list.add(getComponentResult(false,"01","检查分销安排文字描述≥3行",pageNum,"正确","分销安排",textPositionList));
                }else if(start>=0 && end==-1){//判断下一页
                    boolean boo = false;
                    JsonArray _jsonTextDataArray = nextPageModel.getJsonTextData()!=null?nextPageModel.getJsonTextData().getAsJsonArray():null;
                    if(_jsonTextDataArray!=null){
                        for(JsonElement element : _jsonTextDataArray){
                            if(boo) break;
                            JsonArray data = element.getAsJsonObject()!=null?element.getAsJsonObject().getAsJsonArray("data"):null;
                            if(data!=null){
                                for(int i=0;i<data.size();i++){
                                    if(boo) break;
                                    JsonObject current = returnOne(data.get(i).getAsJsonArray());
                                    if(Pattern.matches(nextTitle,current.get("text").getAsString())){
                                        end = i;
                                        boo=true;
                                    }
                                }
                            }
                        }
                    }
                    if(lines-start+end+1>=3){
                        list.add(getComponentResult(false,"01","检查分销安排文字描述≥3行",pageNum,"正确","分销安排",textPositionList));
                    }
                }else{
                    list.add(getComponentResult(false,"02","检查分销安排文字描述≥3行",pageNum,"人工核对","分销安排",textPositionList));
                }
            }else{
                list.add(getComponentResult(false,"02","检查分销安排文字描述≥3行",pageNum,"人工核对","分销安排",null));
            }
        }catch (Exception e){
            list.add(getComponentResult(false,"02","检查分销安排文字描述≥3行",pageNum,"人工核对","分销安排",null));
            log.error(e.getMessage(),e);
        }
        return list;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        return common("BM-3");
    }

    @Override
    public List<ComponentResult> handlerDM() {
        return common("DM-3");
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        return common("BDM-3");
    }



    private ComponentResult getComponentResult(boolean annotationFlag,String exist,String keyword,int pageNum,String promptMsg,String ruleName,List<ComponentResult.TextPosition> textPositionList){
        ComponentResult result = new ComponentResult();
        result.setAnnotationFlag(annotationFlag);
        result.setCatalogId(getCatalogId());
        result.setChapterId(getChapterId());
        result.setExist(exist);
        result.setKeyword(keyword);
        result.setPageNum(pageNum);
        result.setPromptMessage("01".equals(exist)?"正确":promptMsg);
        result.setRegulationId(getRegulationId());
        result.setRuleName(ruleName);
        result.setTextPosition(textPositionList);
        result.setUid(UUID.randomUUID().toString());
        return result;
    }



}
